package com.ng.common.util;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpUtil {

	/**
	 * 发送 POST 请求
	 *
	 * @param urlString       请求的 URL
	 * @param jsonInputString 请求体的 JSON 字符串
	 * @return 响应内容
	 * @throws Exception 可能抛出的异常
	 */
	public static String sendPostRequest(String urlString, String jsonInputString) throws Exception {
		try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
			HttpPost postRequest = new HttpPost(urlString);
			postRequest.setHeader("Content-Type", "application/json; utf-8");
			postRequest.setHeader("Accept", "application/json");

			// 设置请求体
			StringEntity entity = new StringEntity(jsonInputString);
			postRequest.setEntity(entity);

			// 执行请求
			try (CloseableHttpResponse response = httpClient.execute(postRequest)) {
				return EntityUtils.toString(response.getEntity());
			}
		}
	}
}